<template>
  <el-dialog
    title="订单详情"
    :visible.sync="visible"
    width="90%"
    :close-on-click-modal="false"
    append-to-body
    class="seedling-order-detail-dialog"
  >
    <div v-loading="loading" class="order-detail-container">
      <!-- 顶部操作按钮 -->
      <div class="action-buttons">
        <el-button-group v-if="order">
          <el-button 
            type="primary" 
            size="small" 
            :disabled="order.status !== 0" 
            @click="handleAssignNursery"
          >分配育苗点</el-button>
          <el-button 
            type="success" 
            size="small" 
            :disabled="order.status !== 1" 
            @click="handleAssignDriver"
          >分配司机</el-button>
          <el-button 
            type="info" 
            size="small" 
            :disabled="order.status !== 2" 
            @click="handleStartDelivery"
          >开始配送</el-button>
          <el-button 
            type="warning" 
            size="small" 
            :disabled="order.status !== 3" 
            @click="handlePartialReturn"
          >部分退单</el-button>
          <el-button 
            type="success" 
            size="small" 
            :disabled="order.status !== 3" 
            @click="handleComplete"
          >完成订单</el-button>
          <el-button 
            type="warning" 
            size="small" 
            :disabled="!order.driverId" 
            @click="handleChangeDriver"
          >修改司机</el-button>
        </el-button-group>

        <el-button-group>
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-printer" 
            @click="handlePrint"
          >打印订单</el-button>
          <el-button 
            type="primary" 
            size="small" 
            :disabled="!order || !order.demands || order.demands.length <= 1" 
            @click="handleSplitOrder"
          >拆单</el-button>
          <el-button 
            type="danger" 
            size="small"
            :disabled="order && (order.status === 4 || order.status === 5 || order.status === 6)"
            @click="handleDeleteOrder" 
          >删除订单</el-button>
        </el-button-group>
      </div>

      <!-- 状态流转图 -->
      <div class="status-flow">
        <el-steps :active="statusStepActive" finish-status="success" align-center>
          <el-step title="待分配" description="订单创建，等待分配"></el-step>
          <el-step title="已分配育苗点" description="已选择育苗点"></el-step>
          <el-step title="已分配司机" description="已选择配送司机"></el-step>
          <el-step title="配送中" description="订单正在配送"></el-step>
          <el-step title="订单完成" description="订单完成"></el-step>
          <el-step title="部分退单" description="配送中可部分退单" :status="order && order.status === 5 ? 'warning' : 'wait'" />
          <el-step title="已删除" description="任意状态可删除" :status="order && order.status === 6 ? 'error' : 'wait'" />
        </el-steps>
      </div>

      <!-- 订单基本信息 -->
      <el-descriptions title="订单信息" :column="3" border>
        <el-descriptions-item label="订单ID">订单ID：{{ order ? order.orderId : '-' }} </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="order" :type="getOrderStatusType(order.status)">
            {{ order.statusDesc || getStatusText(order.status) }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">创建时间: {{ order ? order.createTime : '-' }} </el-descriptions-item>
        <el-descriptions-item label="育苗点">育苗点: {{ order ? order.deptName : '-' }} </el-descriptions-item>
        <el-descriptions-item label="司机">司机: {{ order ? order.driverName : '-' }} </el-descriptions-item>
        <el-descriptions-item label="司机联系电话">司机联系电话: {{ order ? order.driverPhone : '-' }} </el-descriptions-item>
        <el-descriptions-item label="总数量(亩)">总数量(亩):  {{ order ? order.totalQuantity : '-' }} </el-descriptions-item>
        <el-descriptions-item label="总盘数">总盘数: {{ order ? order.totalPlateQuantity : '-' }} </el-descriptions-item>
        <el-descriptions-item label="备注">备注: {{ order ? (order.remark || '-') : '-' }} </el-descriptions-item>
      </el-descriptions>

      <!-- 子需求列表 -->
      <div class="demand-list-section">
        <h3>订单明细</h3>
        <el-table
          :data="order ? order.demands : []"
          border
          stripe
          style="width: 100%"
          max-height="400px"
        >
          <el-table-column prop="demandId" label="需求ID" width="80" />
          <el-table-column prop="growerName" label="农户名称" min-width="60" />
          <el-table-column prop="seedlingType" label="烟苗品种" min-width="70" />
          <el-table-column prop="quantity" label="需求数量(亩)" width="100" align="right" />
          <el-table-column prop="plateQuantity" label="盘数" width="100" align="right" />
          <el-table-column prop="demandTime" label="需求日期" width="160" />
          <el-table-column prop="statusDesc" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getDemandStatusType(scope.row.status)">
                {{ scope.row.statusDesc }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        </el-table>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { mapState } from 'vuex'

export default {
  name: 'SeedlingOrderDetail',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      loading: false,
      visible: false,
      order: null,
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    statusStepActive() {
      if (!this.order) return 0
      
      switch(this.order.status) {
        case 0: return 0  // 待分配
        case 1: return 1  // 已分配育苗点
        case 2: return 2  // 已分配司机
        case 3: return 3  // 配送中
        case 4: return 4  // 已完成
        case 5: return 5  // 部分退单
        case 6: return 6  // 已删除
        default: return 0
      }
    }
  },
  watch: {
    value(val) {
      this.visible = val
      if (val && this.orderId) {
        this.fetchOrderDetail()
      }
    },
    visible(val) {
      this.$emit('input', val)
    }
  },
  methods: {
    // 获取订单详情
    async fetchOrderDetail() {
      if (!this.orderId) return
      
      try {
        this.loading = true
        const response = await request.get(`/seedling/orders/${this.orderId}`)
        
        // 获取司机联系方式
        if (response.driverId) {
          try {
            const driverInfo = await request.get(`/driver/${response.driverId}`)
            response.driverPhone = driverInfo.phone || '-'
          } catch (error) {
            console.error('获取司机信息失败', error)
            response.driverPhone = '-'
          }
        }
        
        this.order = response
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      } finally {
        this.loading = false
      }
    },

    // 获取订单状态类型
    getOrderStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待分配
        1: 'primary',   // 已分配育苗点
        2: 'success',   // 已分配司机
        3: 'warning',   // 配送中
        4: 'success',   // 已完成
        5: 'danger',    // 部分退单
        6: 'info'       // 已删除
      }
      return statusMap[status] || 'info'
    },

    // 获取需求状态类型
    getDemandStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待分配
        1: 'primary',   // 已生成订单
        2: 'success',   // 已分配育苗点
        3: 'info',      // 已分配司机
        4: 'warning',   // 配送中
        5: 'success',   // 已完成
        6: 'danger',    // 已退单
        7: 'info'       // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待分配',
        1: '已分配育苗点',
        2: '已分配司机',
        3: '配送中',
        4: '已完成',
        5: '部分退单',
        6: '已删除'
      }
      return statusMap[status] || '未知状态'
    },

    // 分配育苗点
    handleAssignNursery() {
      this.$emit('assign-nursery', this.order)
      this.visible = false
    },

    // 分配司机
    handleAssignDriver() {
      this.$emit('assign-driver', this.order)
      this.visible = false
    },
    
    // 修改司机
    handleChangeDriver() {
      this.$emit('change-driver', this.order)
      this.visible = false
    },

    // 开始配送
    handleStartDelivery() {
      this.$emit('start-delivery', this.order)
      this.visible = false
    },

    // 部分退单
    handlePartialReturn() {
      this.$emit('partial-return', this.order)
      this.visible = false
    },

    // 完成订单
    handleComplete() {
      this.$emit('complete-order', this.order)
      this.visible = false
    },

    // 打印订单
    handlePrint() {
      this.$emit('print-order', this.order)
      this.visible = false
    },

    // 拆单
    handleSplitOrder() {
      this.$emit('split-order', this.order)
      this.visible = false
    },

    // 删除订单
    async handleDeleteOrder() {
      try {
        await this.$confirm('确认删除该订单吗？删除后无法恢复。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        this.loading = true
        await request.delete(`/seedling/orders/${this.order.orderId}`)
        this.$message.success('删除订单成功')
        this.$emit('refresh')
        this.visible = false
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除订单失败:', error)
          this.$message.error(error.response?.data?.msg || '删除订单失败')
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-container {
  padding: 0 10px;
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .status-flow {
    margin: 30px 0;
    
    .el-steps {
      padding: 0 10%;
    }
  }
  
  .demand-list-section {
    margin-top: 30px;
    
    h3 {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 15px;
      color: #303133;
    }
  }
  
  .order-summary-section {
    margin-top: 30px;
    
    h3 {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 15px;
      color: #303133;
    }
    
    .order-summary-content {
      padding: 10px;
      background-color: #f5f7fa;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      font-size: 14px;
      line-height: 1.5;
      color: #303133;
    }
  }
}

.dialog-footer {
  text-align: right;
}

.seedling-order-detail-dialog {
  .el-dialog__body {
    padding-top: 10px;
  }
}
</style> 